import time
import urllib.parse
from app.doc.get_cookies import Cookies
import requests
import logging


class get_all_data():
    data = {}
    headers = {
        'Host': 'app.gsxt.gov.cn',
        'Content-Type': 'application/json;charset=utf-8',
        'Connection': 'keep-alive',
        'Content-Length': '200',
        'Accept': 'application/json',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0',
        'Accept-Language': 'zh-cn',
        'Accept-Encoding': 'gzip, deflate',
        'X-Requested-With': 'XMLHttpRequest'
    }
    cookies = Cookies()

    def get_list_data(self, keyword):
        self.data = {}
        datas = []
        try:
            datas = self.cookies.get_cookies()
            logging.info(f"cookies数据为：{datas}")
            if datas:
                url = "http://app.gsxt.gov.cn/gsxt/cn/gov/saic/web/controller/PrimaryInfoIndexAppController/search?page=1"
                data = {
                    "searchword": urllib.parse.quote(keyword),
                    "conditions": {"excep_tab": "0", "ill_tab": "0", "area": "0", "cStatus": "0", "xzxk": "0",
                                   "xzcf": "0",
                                   "dydj": "0"}, "sourceType": "I"}
                self.headers['Proxy-Authorization'] = datas[2]
                respose = requests.post(url, headers=self.headers, json=data, proxies=datas[1], verify=False,
                                        cookies=datas[0], timeout=(10, 10))
                if respose.status_code == 200:
                    respose = respose.json()
                    logging.info(f'搜索接口响应：{respose}')
                    if "NGIDERRORCODE" not in respose.keys():
                        self.get_details_url(respose, datas[0], datas[1])
                else:
                    self.data['list_code'] = respose.status_code
                    logging.info(f"搜索接口响应code:{respose.status_code}")
                    logging.info(f"搜索接口响应：{respose.text}")
            else:
                logging.info(f"cookie获取数据：{datas}")
                return self.data
            logging.info(f"返回视图的数据：{self.data}")
            return self.data
        except Exception as e:
            logging.error(f"cookies的值是{datas[0] if len(datas) > 0 else datas}")
            logging.error(f"proxies的值是{datas[1] if len(datas) > 0 else datas}")
            logging.error(f"Proxy_Authorization的值是{datas[2] if len(datas) > 0 else datas}")
            logging.error(e, exc_info=True)
            return self.data

    def get_details_url(self, response, cookies, proxies):
        details_data = []
        try:
            if 'NGIDERRORCODE' not in response.keys():
                a = 0
                for i in response['data']['result']['data']:
                    url_list = f"http://app.gsxt.gov.cn/gsxt/corp-query-entprise-info-primaryinfoapp-entbaseInfo-{i['pripid']}.html?" \
                               f"nodeNum={i['nodeNum']}&entType={i['entType']}&sourceType=I"
                    resposelist = requests.post(url_list, headers=self.headers, json={}, proxies=proxies, verify=False,
                                                cookies=cookies, timeout=(10, 10))
                    logging.info(f"详情页接口响应_{str(a)}：{resposelist.text}")
                    if resposelist.status_code == 200:
                        resposelist = resposelist.json()
                        if 'NGIDERRORCODE' not in resposelist.keys():
                            details_data.append(resposelist)
                        # self.get_details_data(resposelist, cookies, proxies)
                    else:
                        self.data['details_code_' + str(a)] = resposelist.status_code
                    a = a + 1
                self.data['details_data'] = details_data
        except Exception as e:
            logging.error(e, exc_info=True)
            self.data['details_data'] = details_data

    def get_details_data(self, response, cookies, proxies):
        try:
            if 'NGIDERRORCODE' not in response.keys() and 'result' in response.keys():
                url_shareholder = f"http://app.gsxt.gov.cn/gsxt/corp-query-entprise-info-shareholder-{response['result']['pripId']}.html?" \
                                  f"nodeNum={response['result']['nodeNum']}&entType={response['result']['entType']}&start=0&sourceType=I"
                resposeshareholder = requests.post(url_shareholder, headers=self.headers, json={}, proxies=proxies,
                                                   verify=False,
                                                   cookies=cookies, timeout=(10, 10))
                respose_shareholder = resposeshareholder.json() if resposeshareholder.status_code == 200 else resposeshareholder.text
                logging.info(f"股东接口响应：{respose_shareholder}")
                self.data['respose_shareholder'] = respose_shareholder
            else:
                logging.info(f"详情页接受的response：{response}")
        except Exception as e:
            logging.error(f"response的值是{response}")
            logging.error(e, exc_info=True)
